import React, {ChangeEvent, useState} from 'react';
import style from './EditHeader.module.scss'
import {Button, Input, message, Space, Typography} from "antd";
import {EditOutlined, LeftOutlined, LoadingOutlined} from '@ant-design/icons'
import {useNavigate, useParams} from "react-router-dom";
import EditToolbar from "./EditToolbar";
import useGetPageInfo from "../../../hooks/useGetPageInfo";
import {useDispatch} from "react-redux";
import {changePageInfoTitle} from "../../../redux/pageinfoReducer";
import useGetComponentInfo from "../../../hooks/useGetComponentInfo";
import {useDebounceEffect, useKeyPress, useRequest} from "ahooks";
import {updateQuestionService} from "../../../service/question";

const {Title} = Typography
const TitleElem = () => {
  const {title} = useGetPageInfo()
  const [editState, setEditState] = useState(false);
  const dispatch = useDispatch()
  if (editState) {
    return <Input value={title}
                  onChange={handleChange}
                  onBlur={() => setEditState(false)}
                  onPressEnter={() => setEditState(false)}/>
  }

  function handleChange(event: ChangeEvent<HTMLInputElement>) {
    const newValue = event.target.value.trim()
    if (!newValue) return
    dispatch(changePageInfoTitle(newValue))
  }

  return <Space direction={"horizontal"}>
    <Title level={3}>
      {title}
    </Title>
    <Button icon={<EditOutlined/>} type={'text'} onClick={() => setEditState(true)}></Button>
  </Space>
}

const SaveButton = () => {
  const {componentList} = useGetComponentInfo()
  const pageInfo = useGetPageInfo()
  const {id} = useParams()
  useKeyPress(['ctrl.s', 'meat.s'], (event: KeyboardEvent) => {
    event.preventDefault()
    if (!loading) save()
  })
  // 自动保存，防抖
  useDebounceEffect(() => {
    save()
  }, [componentList, pageInfo], {
    wait: 500
  })
  const {loading, run: save} = useRequest(async () => {
    if (!id) return
    await updateQuestionService(id, {...pageInfo, componentList})
  }, {
    manual: true
  })
  return <Button disabled={loading} onClick={save} icon={loading ? <LoadingOutlined/> : null}>保存</Button>
}

const PublishButton = () => {
  const {componentList} = useGetComponentInfo()
  const pageInfo = useGetPageInfo()
  const {id} = useParams()
  const nav = useNavigate()
  const {loading, run: publish} = useRequest(async () => {
    if (!id) return
    await updateQuestionService(id, {
      ...pageInfo,
      componentList,
      isPublished: true
    })
  }, {
    manual: true,
    onSuccess() {
      message.success("发布成功")
      nav(`/question/stat/${id}`)
    }
  })
  return <Button type={'primary'} onClick={publish} icon={loading ? <LoadingOutlined/> : ""}>发布</Button>
}

const EditHeader: React.FC = () => {
  const nav = useNavigate()
  return (
    <div className={style['header-wrapper']}>
      <div className={style['header']}>
        <div className={style['left']}>
          <Space>
            <Button type={"link"} icon={<LeftOutlined/>} onClick={() => nav(-1)}>返回</Button>
            <TitleElem/>
          </Space>
        </div>
        <div className={style['main']}>
          <EditToolbar/>
        </div>
        <div className={style['right']}>
          <SaveButton/>
          <PublishButton/>
        </div>
      </div>
    </div>
  );
};

export default EditHeader;
